from PySide2.QtCore import *
from ssh.ssh_client import Ssh_client
import logging
import textfsm
import os
import openpyxl
import time
import datetime
from openpyxl.styles import PatternFill
from uitil.CXlAutofit import CXlAutofit

class Ssh_signal(QObject):
    task_done = Signal()
    send_logs = Signal(str)
    timer_stop = Signal()

class Ssh_worker(QObject):

    def __init__(self, ssh_data:dict) -> None:
        super().__init__()
        self.ssh_data =  ssh_data
        self.log = logging.getLogger('app_log')
        self.signal = Ssh_signal()

    finished = Signal()

    def start_work(self):
        print('执行script')
        ssh_data = self.ssh_data
        self.client = Ssh_client(ssh_data['ip'],
                                 ssh_data['user'],
                                 ssh_data['password'],
                                 ssh_data['port'])

        cmds = ssh_data['cmds'].split('\n')
        if self.client.connect_server():
            log_text = f'ssh连接设备 {ssh_data["ip"]} 成功!'
            self.signal.send_logs.emit(log_text)
            self.log.info(log_text)
            if self.client.init_invoke():
                log_text = f'{ssh_data["ip"]}初始化invoke成功!'
                self.signal.send_logs.emit(log_text)
                self.log.info(log_text)

                echos = self.client.send_commands(cmds)
                self.log.info(echos)
                self.signal.send_logs.emit(echos)

                print('执行textfsm')
                # 生成模板文件
                with open ('textfsm_temp_file.template','w') as template:
                    template.write(ssh_data['textfsm'])
                # textfsm 过滤数据
                with open ('textfsm_temp_file.template') as template:
                    try:
                        textfsm_table = textfsm.TextFSM(template)
                        out_data = textfsm_table.ParseText(echos)
                        print(textfsm_table.header)
                        print(out_data)
                    except Exception as e:
                        print(e) 

            # openxl 写入数据
                # file_path .\维护记录\日期\设备名.xlsx
                # 保障目录文件存在
                if not os.path.exists('维护记录'):
                    os.mkdir('维护记录')
                
                date = datetime.date.today().strftime('%Y-%m-%d')
                if not os.path.exists(f'维护记录\\{date}'):
                    os.mkdir(f'维护记录\\{date}')
                
                path = f'维护记录\\{date}\\'
                workbook_file =  path + ssh_data['device_name'] + '.xlsx'
                if not os.path.exists(workbook_file):
                    workbook = openpyxl.Workbook()
                    workbook.save(workbook_file)

                # 保障表格存在
                blank_row = 0
                workbook = openpyxl.load_workbook(workbook_file)
                shts = workbook.sheetnames
                create_sht = True
                sht_name = ssh_data['script_name']
                for name in shts:
                    if name == sht_name:
                        create_sht = False
                        blank_row = 4
                    if name =='Sheet':
                        workbook.remove_sheet(workbook['Sheet']) #删除默认sheet
                if create_sht:
                    workbook.create_sheet(sht_name)
                sht = workbook[sht_name]

                # 如果存在表格 则续写
                max_row = sht.max_row + blank_row
                # 写入时间
                cell = sht.cell(max_row,1,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
                sht.merge_cells(start_row=max_row,end_row=max_row,
                                start_column=1,
                                end_column= len(textfsm_table.header) if len(textfsm_table.header)>1 else 1)
                cell.fill = PatternFill(start_color='F2FF00',end_color='F2FF00',fill_type='solid')
                # 写入标题
                max_row += 1
                col = 1
                title = textfsm_table.header
                for s in title:
                    sht.cell(max_row,col,s)
                    col += 1
                #写入数据
                row = max_row + 1
                for l in out_data:
                        for i in range(0,len(l)):
                            c = sht.cell(row,i+1,l[i])
                            # c.fill = PatternFill(start_color='1EFF0000',end_color='1EFF0000',fill_type='solid')
                        row += 1

                workbook.save(workbook_file)
                # 自适应列宽
                cx = CXlAutofit()
                cx.style_excel(workbook_file,sht_name)
                self.signal.send_logs.emit(f'保存文件 {ssh_data["device_name"]}.xlsx')
                self.log.info(f'保存文件 {ssh_data["device_name"]}.xlsx')
            else:
                log_text = f'设备 {ssh_data["ip"]} 初始化invoke失败!'
                self.signal.send_logs.emit(log_text)
                self.log.warning(log_text)
        else:
            log_text = f'ssh连接设备 {ssh_data["ip"]} 失败!'
            self.signal.send_logs.emit(log_text)
            self.log.warning(log_text)
 
        self.finished.emit()


    def stop_worker(self):
        print('结束worker')
        self.finished.emit()
